package com.spring.boot.util;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class HttpTools {


    /**
     * post form-data 发送文件
     * 该方法会自动识别上传类型，理论上，所有的http请求类型都可以用
     * @throws IOException
     */
    public void postFile() throws IOException {

        String urlStr = "http://192.168.1.235:80/ai/vehicle/setting";
//        String urlStr = "http://192.168.1.235:80/ai/vehicle/push";
        String fileStr = "/home/god/Desktop/women.jpeg";


        String httpMethod = urlStr;
        RestTemplate restTemplate = new RestTemplate();
//        String args = "";

        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("user_id", 39);
        paramMap.add("operate", 2);
//        paramMap.add("uuid", 3);

        File file=new File(fileStr);
        byte[] bytesArray = new byte[(int) file.length()];

        FileInputStream fis = new FileInputStream(file);
        fis.read(bytesArray); //read file into bytes[]
        fis.close();
        String filename = "file";
        ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
            @Override
            public String getFilename() {
                return filename;
            }
        };
        paramMap.add("file", contentsAsResource);
        String s = restTemplate.postForObject(httpMethod, paramMap, String.class);

        System.out.println("result : " + s);

    }


}
